import ccxt
from vnpy.event.engine import EventEngine
import time
from vnpy.trader.engine import MainEngine
from vnpy.app.data_recorder.engine import RecorderEngine
import pandas as pd
import okex.futures_api as Futures
'''
A3 策略流程：
监控4小时 16个5分钟的成交均价
档当前价格 偏离4.5% 买入  再偏离4.5% 再买入 直到爆仓
当价格回归到 均价即平仓
'''
# 创建一个交易所对象exchange
API ={}
#--------------------------------------------------------------------------------------------------------#
exchange2 = Futures.FutureAPI(api_key='91345c11-a64d-4ea9-b588-f31fe4bc57c2',api_seceret_key='FE9739655771B5C8573512392D8032F4',passphrase='zhubiao111')
exchange = ccxt.okex3(config= API)
# 采集数据
def  start_main():
    kline = exchange2.get_kline(instrument_id='EOS-USD-190927',granularity='1m') # 获取到当时的
    df = pd.DataFrame(kline,dtype='float')
    df.rename(columns = {0:'Date',1:'Open',2:'High',3:'Low',4:'Close',5:'volume',6:'currency_volume'},inplace=True)
    #--------------------------------------------------------------------------------------------------------
    #请求的数据是逆序的 所以需要重新排序
    df.set_index('Date',inplace=True)
    df.sort_index(inplace=True)
    df.reset_index(level=0,inplace=True)
    #---------------------------------------------------------------------------------------------------------
    '''计算16条线各自的均价'''
    NOW_Price = df['Close'].loc[len(df)-1] #当前价格

    ancount_price   = [None]*16 # 创建一个空列表 用来保存16条的 均价
    ancount_amount  = [None]*16
    MA_price        = [None]*16

    for i in range (16):
        ancount_price[i] = df['volume'].iloc[len(df)-15*(i+1):len(df)-15*i].sum()*10  #总交易金额
        ancount_amount[i] = df['currency_volume'].iloc[len(df)-15*(i+1):len(df)-15*i].sum() #交易总币数
        MA_price[i] =  ancount_price[i]/ancount_amount[i]
    #----------------------------------------------------------------------------------------------------------
    ''' 计算16个15分钟的成交均价'''
    true_MAprice = sum(MA_price)/16
    #-----------------------------------------------------------------------------------------------------------
    '''计算当前的价差百分比
    当前价格 / 4小时均价 -1
    如果大于等于 4.5% 开一个反向的单
    如果继续拉大价差 并单 以并单的价格平一部分？？？
    '''
    pont = NOW_Price/true_MAprice -1 # 计算价差如果达到4.5% 开单
    return NOW_Price,pont

def on_log(info):
    with open('log.txt',mode='a') as f:
        f.write(info+'\n')

    f.close()


if __name__ == '__main__':
    flage =0
    while True:
        try:
           now_time ,pont = start_main()


        except Exception as e :
            print(e)

        if pont >=0.045 and flage ==0:
            timenow =time.time()
            on_log('当前价差大于4.5%:  '+str(timenow)+'当前价差：'+str(pont))
            flage =-1 #开空单

        if pont <=-0.045 and flage ==0:
            timenow = time.time()
            on_log('当前价格小于4.5%:  '+str(timenow)+'当前价差：'+str(pont))
            flage = 1

        # if flage == 1 or flage == -1:
        print('当前价格差：',pont)
        time.sleep(0.5)




